<?php
class MembersController extends AppController {
	var $name = 'Members';
    var $components = array('Email');
    var $country = array(
        'AR' => 'Argentina',
        'AU' => 'Australia',
        'BS' => 'Bahamas',
        'BH' => 'Bahrain',
        'BZ' => 'Belize',
        'BM' => 'Bermuda',
        'BR' => 'Brazil',
        'VG' => 'British Virgin Islands',
        'CA' => 'Canada',
        'KY' => 'Cayman Islands',
        'CL' => 'Chile',
        'CN' => 'China',
        'CR' => 'Costa Rica',
        'DO' => 'Dominican Republic',
        'EC' => 'Ecuador',
        'GU' => 'Guam',
        'GT' => 'Guatemala',
        'HK' => 'Hong Kong',
        'IN' => 'India',
        'IL' => 'Israel',
        'JP' => 'Japan',
        'JO' => 'Jordan',
        'KW' => 'Kuwait',
        'MO' => 'Macau',
        'MY' => 'Malaysia',
        'MX' => 'Mexico',
        'NZ' => 'New Zealand',
        'PA' => 'Panama',
        'PE' => 'Peru',
        'PH' => 'Philippines',
        'SA' => 'Saudi Arabia',
        'SG' => 'Singapore',
        'ZA' => 'South Africa',
        'KR' => 'South Korea',
        'LK' => 'Sri Lanka',
        'TW' => 'Taiwan',
        'TH' => 'Thailand',
        'VI' => 'U.S. Virgin Islands',
        'AE' => 'United Arab Emirates',
        'US' => 'United States',
        'UM' => 'United States Minor Outlying Islands',
        'VE' => 'Venezuela'
    );

    public function admin_listData ($type=null) {
        $rs = $this->Member->accountList($this->params['form']);

        $json = ($rs) ? $rs : array(
            'page'  => 1,
            'total' => 0,
            'rows'  => array()
        );

        $this->response($json);
    } // admin_listData

    public function admin_dashboard () {
        $this->pageTitle = __('Dashboard', true);
        $this->set('pageTitle', $this->pageTitle);
    } // admin_dashboard

    public function login () {
        if ($this->RequestHandler->isAjax()) {
            if (isset($this->params['form']['username']) && isset($this->params['form']['password'])) {
                $data = $this->Member->find('first', array(
                    'conditions' => array('username'=>$this->params['form']['username'], 'password' => $this->params['form']['password']),
                    'recursive'  => -1,
                    'fields'     => 'id, role'
                ));

                if (isset($data['Member']['id'])) {
                    $this->Member->id = $data['Member']['id'];

                    $json = array('status'=>true, 'role'=>$data['Member']['role']);
                    $this->Session->write('Member', array(
                        'id'       => $data['Member']['id'],
                        'username' => $this->params['form']['username'],
                        'role'     => $data['Member']['role']
                    ));
                } else {
                    $json = array(
                        'status' => false,
                        'mesg'   => __('Invalid login, please try again..', true)
                    );
                }
            } else {
                $json = array(
                    'status' => false,
                    'mesg'   => __('Please enter username and password..', true)
                );
            }

            $this->response($json);
            return;
        } else if ($this->Session->read('Member.id')) { // already logged mah..
            $this->redirect('/pages/home');
        }

        $this->pageTitle = __('Account Login', true);
        $this->set('pageTitle', $this->pageTitle);
    } // login

    public function logout () {
        $bool = $this->Session->del('Member');
        $this->redirect('/pages/home');
    } // logout

    public function register () {
        if ($this->RequestHandler->isAjax()) {
            $this->data['Member'] = $this->params['form'];

            $valid = true;
            $empty = array('fax');

            foreach ($empty as $fieldname) {
                if (isset($this->data['Member'][$fieldname]) && !$this->data['Member'][$fieldname]) {
                    $this->data['Member'][$fieldname] = null;
                }
            }

            $this->Member->set($this->data);

            if ($this->Member->validates() && $valid) { // data validated!
                if ($this->Member->save($this->data)) {
                    $mesg = empty($this->params['form']['id']) ? __('Your account has been created successfully!',true) : __('Your account has been updated successfully!',true);
                    $json = array(
                        'status' => true,
                        'mesg'   => $mesg
                    );

                    $this->Session->write('Member', array(
                        'id'       => $this->Member->id,
                        'username' => $this->params['form']['username'],
                        'role'     => 'M'
                    ));
                } else { // invalid email uses or fail insert record
                    $mesg = empty($this->params['form']['id']) ? __('Fail register account at this time, please try again.',true) : __('Fail update your account at this time, please try again.',true);
                    $err  = ($this->error) ? $this->error : $mesg;
                    $json = array(
                        'status' => false,
                        'mesg'   => $err
                    );
                }
            } else { // invalid data found
                $json = array(
                    'status' => false,
                    'mesg'   => __('Please enter the requested details in the fields pointed out below and try again!', true)
                );
                foreach ($this->Member->invalidFields() as $k=>$v) {
                    $k = ($k == 'username') ? 'username01' : $k;
                    $k = ($k == 'password') ? 'password01' : $k;
                    $json['error'][] = array('id'=>$k, 'field'=>$k, 'code'=>$v);
                }
            }
            $this->response($json);
            return;
        }

        $this->pageTitle = __('Create Account', true);
    } // register

    public function forgot () {
        if ($this->RequestHandler->isAjax()) {
            $form = $this->params['form'];

            if (empty($form['email'])) {
                $json = array(
                    'status' => false,
                    'mesg'   => __('Email address field is required', true)
                );
            } else if (!$this->Member->find('count', array('conditions'=>array('Member.username'=>$form['email']), 'recursive'=>-1))) {
                $json = array(
                    'status' => false,
                    'mesg'   => __('The email address you entered has not been registered, please try again!', true)
                );
            } else {
                $this->_sendPassword($form['email']);
                $json = array(
                    'status' => true,
                    'mesg'   => r('%email%', $form['email'], __('An email has been sent to %email% for obtain your password',true))
                );
            }

            $this->response($json);
            return;
        }

        $this->pageTitle = __('Forgot Your Password?', true);
    } // forgot

    public function success () {
        $this->pageTitle = __('Your Account Has Been Created!', true);
    } // success

    public function update () {
        if (!$this->_checkLogged()) {
            return;
        }

        if ($this->RequestHandler->isAjax()) {
            $data = $this->Member->read(null, $this->Session->read('Member.id'));
            $data['Member'] = array_merge($data['Member'], $this->params['form']);

            $this->Member->set($data);

            if ($this->Member->validates()) { // data validated!
                if ($this->Member->save()) {
                    $mesg = __('Your account has been updated successfully!',true);
                    $json = array(
                        'status' => true,
                        'mesg'   => $mesg
                    );
                } else {
                    $mesg = __('Fail update your record to database at this time, please try again.',true);
                    $err  = ($this->error) ? $this->error : $mesg;
                    $json = array(
                        'status' => false,
                        'mesg'   => $err
                    );
                }
            } else { // invalid data found
                $json = array(
                    'status' => false,
                    'mesg'   => __('Please enter the requested details in the fields pointed out below and try again!', true)
                );
                foreach ($this->Member->invalidFields() as $k=>$v) {
                    $k = ($k == 'username') ? 'username01' : $k;
                    $json['error'][] = array('id'=>$k, 'field'=>$k, 'code'=>$v);
                }
            }

            $this->response($json);
            return;
        } else {
            $data = $this->Member->find('first', array(
                'conditions' => array(
                    'id' => $this->Session->read('Member.id')
                ),
                'recursive'  => -1
            ));

            $this->pageTitle   = __('Member Information Modify', true);
            $this->set('pageTitle', $this->pageTitle);
            $this->set('member', $data['Member']);
        }
    } // update

    public function password () {
        if (!$this->_checkLogged()) {
            return;
        }

        if ($this->RequestHandler->isAjax()) {
            if (!empty($this->params['form']['old_password']) || !empty($this->params['form']['password'])) {
                $data = $this->Member->find('count', array(
                    'conditions' => array(
                        'id'       => $this->Session->read('Member.id'),
                        'password' => $this->params['form']['old_password']
                    ),
                    'recursive'  => -1
                ));

                if (!$data) {
                    $json = array(
                        'status' => false,
                        'mesg'   => __('You have enter an incorrect old password!', true)
                    );
                    $json['error'][] = array('id'=>'old_password', 'field'=>'old_password', 'code'=>__('incorect password',true));
                    $this->response($json);
                    return;
                }

                $this->Member->id = $this->Session->read('Member.id');
                $this->Member->saveField('password', $this->params['form']['password']);
                $mesg = __('Your password has been changed successfully!',true);
                $json = array(
                    'status' => true,
                    'mesg'   => $mesg
                );
            } else {
                $json = array(
                    'status' => false,
                    'mesg'   => __('Please enter old and new password!', true)
                );
            }

            $this->response($json);
            return;
        } else {
            $this->pageTitle   = __('Member Password Modify', true);
            $this->set('pageTitle', $this->pageTitle);
        }
    } // password

    public function index () {
        if (!$this->_checkLogged()) {
            return;
        }

        $this->pageTitle = __('Member Area', true);
        $this->set('pageTitle', $this->pageTitle);
    } // index

    public function shipping () {
        if (!$this->_checkLogged()) {
            return;
        }

        $id   = $this->Session->read('Member.id');
        $role = $this->Session->read('Member.role');

        if (!$id) {
            $this->redirect('/members/login');
        } else if ($role == 'A') {
            $this->redirect('/pages/home');
        }

        $info = $this->Session->read('Info');
        if (is_array($info) && count($info)>0) {
            $data = array(
                'Member' => $info
            );
        } else {
            $data = $this->Member->read(null, $id);
        }

        $this->pageTitle = __('Payment Information', true);
        $this->set('data', $data);
        $this->set('country', $this->country);
    } // shipping


    private function _sendPassword ($email) {
        $sitename = Configure::read('site.sitename');
        $domain   = str_replace('www.', '', env('HTTP_HOST'));
        $subject  = 'Your password on CareLatex.com';
        $sendFrom = 'noreply@'.$domain;

        $this->Email->to       = $email;
        $this->Email->replyTo  = $sendFrom;
        $this->Email->from     = $sitename.' <'.$sendFrom.'>';
        $this->Email->subject  = $subject;
        $this->Email->template = 'send_password';
        $this->Email->sendAs   = 'text';
        $this->Email->delivery = 'mail';

        $params = array(
            'conditions' => array('username'=>$email),
            'recursive'  => -1,
            'fields'     => 'Member.name, Member.password'
        );
        $data = $this->Member->find('first', $params);
        $data = array(
            'name'      => $data['Member']['name'],
            'password'  => $data['Member']['password'],
            'sitename'  => $sitename
        );

        $this->set($data);
        $this->Email->send();

        if (isset($this->Email->smtpError)) {
            return $this->Email->smtpError;
        }

        return;
    } // _sendPassword
} // MembersController
?>